package com.powernode.filter;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.powernode.constant.AuthConstants;
import com.powernode.model.SecurityUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * token转换过滤器
 */
@Component
public class TokenTranslationFilter extends OncePerRequestFilter {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * token转换过滤器
     * 前提：只负责处理携带token的请求，然后将认证的用户信息转换出来
     * 没有携带token的请求，交给security资源配置类中的处理器进行处理
     * token有值 ，转为用户信息，并将之转我security框架认证的用户信息对象，再将
     * @param request 请求
     * @param response 响应
     * @param filterChain 过滤器链
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //从请求头中获取Authorization的值：格式为：bearer：token
        String authorizationValue = request.getHeader(AuthConstants.AUTHORIZATION);
        //判断是否有值
        if (StrUtil.isNotBlank(authorizationValue)){
            //获取token
            String token = authorizationValue.replaceFirst(AuthConstants.BEARER, "");
            //判断token是否有值
            if (StrUtil.isNotBlank(token)){

                //刷新token有效期
                stringRedisTemplate.expire(AuthConstants.LOGIN_TOKEN_PREFIX+token,AuthConstants.TOKEN_TIME, TimeUnit.MINUTES);


                //从redis中获取json格式字符串的认证用户信息
                String userJsonStr = stringRedisTemplate.opsForValue().get(AuthConstants.LOGIN_TOKEN_PREFIX + token);
                //将json格式字符串的认证用户信息转为认证用户对象
                SecurityUser securityUser = JSONObject.parseObject(userJsonStr, SecurityUser.class);
                //处理权限
                Set<SimpleGrantedAuthority> collect = securityUser.getPerms().stream().map(SimpleGrantedAuthority::new).collect(Collectors.toSet());

                //UsernamePasswordAuthenticationToken的形参：用户信息、凭证（此处为空）和权限集合(set:唯一易于查找)
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(securityUser,"",collect);
                //将认证用户对象存放到当前模块的上下方中
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);

            }
        }
        filterChain.doFilter(request,response);
    }
}
